<template>
  <div class="view-fill">
    <div v-if="!showDetails && !detailDialog" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-deptName>
                <el-input
                  v-if="isSpecialEdit === 1"
                  v-model="formInfo.data.deptName"
                  disabled
                ></el-input>
                <el-input
                  v-else
                  v-model="formInfo.data.deptName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择部门"
                >
                  <template #append>
                    <el-icon @click="openDeptWindow"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
            <div class="model-tips">
              (证照：<span>近效期</span>
              <span class="model-tips-nearly"></span>
            </div>
            <div class="model-tips">
              <span>过期</span>
              <span class="model-tips-expire"></span>)
            </div>
          </div>
          <div class="model-panel-body">
            <div class="filter-wrapper">
              <!-- 条件栏 -->
              <page-filter
                v-model:query="filterInfo.query"
                :filter-list="filterInfo.list"
              >
                <template v-slot:filter-addProduct>
                  <el-button :disabled="!canAddProduct" @click="addProduct"
                    >添加产品</el-button
                  >
                </template>
                <template v-slot:filter-removeProduct>
                  <el-button
                    :disabled="!canRemoveProduct"
                    @click="removeProduct()"
                    >删除产品</el-button
                  >
                </template>
                <template v-slot:filter-selectTemplate>
                  <el-button
                    :disabled="!formInfo.data.deptId || isSpecialEdit === 1"
                    @click="selectTemplate"
                    >选择模板</el-button
                  >
                </template>
              </page-filter>
              <div class="display-flex">
                <el-button @click="preferenceInfo.visible = true"
                  >偏好设置</el-button
                >
              </div>
            </div>

            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  ref="table"
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="true"
                  :query="filterInfo.query"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :cell-class-name="tableCellClassName"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-qty="scope">
                    <el-form-item class="margin-bottom">
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item ss">
                            <el-form-item
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positiveAndZero,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.largeUnitQty"
                                clearable
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                @change="
                                  changeLarge(
                                    $event,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                                :min="0"
                                :max="largeMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div>
                          </div>
                          <div
                            class="page-table-input-number-item ww"
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                          >
                            <el-form-item>
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.smallUnitQty"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :min="0"
                                :max="smallMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div>
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-right"
                          v-if="scope.row.qtyOperateMode === 2"
                        >
                          {{ $fn.qtyFormatter(scope.row.qty) }}
                        </div>
                      </div>
                    </el-form-item>
                  </template>
                  <template v-slot:col-price="scope">
                    <p>{{ scope.row.price }}</p>
                    <p
                      style="color: red"
                      v-if="
                        scope.row.isLimitPrice == 1 &&
                        scope.row.price > scope.row.purchaseLimitPrice
                      "
                    >
                      超过产品限价:{{ scope.row.purchaseLimitPrice }}
                    </p>
                  </template>
                </page-table>
              </el-form>
            </div>
            <NewSelectProduct
              v-if="productInfo.visible"
              v-model:show-dialog="productInfo.visible"
              :query="productInfo.query.queryMap"
              :query-params="productInfo.query.queryParams"
              :api="productInfo.api"
              :table-key="productInfo.tableKey"
              :show-price="productInfo.priceShow"
              :checkBoxSlotObj="checkBoxSlotObj"
              @callback="selectProduct"
            />

            <selectDept
              v-if="deptInfo.visible"
              v-model:show-dialog="deptInfo.visible"
              :check-box="deptInfo.checkBox"
              :highlight-row="true"
              :query="deptInfo.query"
              :saveEmpty="true"
              @callback="_selectDept"
            />

            <select-purch-template
              v-if="purchTemplateInfo.visible"
              v-model:show-dialog="purchTemplateInfo.visible"
              :check-box="true"
              :highlight-row="false"
              :tab-index="true"
              :query="purchTemplateInfo.query"
              @callback="selectPurchTemplateCallback"
            />
          </div>
        </div>
      </NewFullScreen>
    </div>
    <licenseDetails
      v-if="showDetails"
      :id="licenseId"
      v-model:visible="showDetails"
    ></licenseDetails>
    <product-details
      v-if="detailDialog"
      :id="detailId"
      v-model:visible="detailDialog"
    />
    <SetPreferenceNoQuery
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      tableKey="productPurchApplicationPage-com.slip.spd.entity.vo.core.CoreProductVONew"
      @callback="setPreferenceCallback"
    />
  </div>
</template>

<script setup name="purchApplicationModify">
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index.vue'
import {
  purchApplicationDetailCustomizeListAll,
  createPurchApplication,
  createPurchApplicationAndSave,
  updatePurchApplication,
  getPurchTemplateDetailAll,
  submitPurchApplication,
  postPurchProductWithStock,
  getPurchApplication,
  applicationsValidatePlanRemind,
} from '@/api/purch'
import PageFilter from '@/components/PageFilter/index'
import SelectPurchTemplate from '@/components/SelectPurchTemplate/index'
import selectDept from '@/components/SelectDept/index'
import { getCoreSystemConfigGetConfigValue } from '@/api/core.js'
import { getLastAndDeptStock } from '@/api/stock.js'
import licenseDetails from '../../product/license/details'
import ProductDetails from '../../product/product/details'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { selectDeptProduct } from '@/api/core'

const NewSelectProduct = defineAsyncComponent(() =>
  import('@/components/NewSelectProduct/index')
)
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const SetPreferenceNoQuery = defineAsyncComponent(() =>
  import('@/components/SetPreference/setPreferenceNoQuery')
)

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
  orderId: {
    type: [Number, String],
    default: '',
  },
  isSpecialEdit: {
    type: [Number, String],
    default: '',
  },
  isCopy: {
    type: Boolean,
    default: false,
  },
})
const checkBoxSlotObj = ref({
  // 搜索按钮后显示复选框
  showCheckBox: true,
  checkBoxBool: false,
  otherBusinessType: 'application',
  otherBusinessTableKey:
    'productRecentlyApplicationPage-com.slip.spd.entity.vo.core.CoreProductVONew',
  // 复选框文件描述
  checkLabel: '最近申购产品排前',
  // 复选框点击选中传值
  checkParams: {
    recentlyApplication: 1,
  },
  // 复选框未选中传值
  noCheckParams: {
    recentlyApplication: null,
  },
})
const formInfo = reactive({
  ref: null,
  data: {
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    createUserName: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : '',
    purchProductType: 1,
  },
  fieldList: [
    {
      label: '创建人',
      value: 'createUserName',
      type: 'input',
      disabled: true,
    },
    { label: '部门', value: 'deptName', type: 'slot' },
    {
      label: '是否临采',
      value: 'temporaryPurch',
      type: 'select-model',
      code: 'default_no_or_yes',
      disabled: props.isSpecialEdit !== 1 ? false : true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    deptName: [{ required: true, message: '请选择部门', trigger: 'change' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      deptId: null,
      isCopy: props.isCopy,
    },
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'selectTemplate' },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  selectionsCopy: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
})
const fullInfo = reactive({
  btnList: [
    {
      label: '保存并提交',
      event: saveAndSubmit,
      show:
        (!props.orderId || props.isCopy) &&
        proxy.$permission('purchApplication:saveAndSubmit'),
    },
    { label: '保存', event: save, show: true },
  ],
})
//选择产品相关
let productInfo = reactive({
  visible: false,
  api: postPurchProductWithStock,
  priceShow: proxy.$permission('purchApplication:price'),
  tableKey:
    'productPurchApplicationPage-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      status: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      putShelfStatus: {
        asTbName: 'core_product_new',
        columnName: 'put_shelf_status',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {
      deptId: null,
      checkDeptProduct: 1,
    },
  },
  searchList: [],
})
const deptInfo = reactive({
  visible: false,
  checkBox: false,
  query: {
    deptAuth: 'id',
  },
})
const purchTemplateInfo = reactive({
  visible: false,
  query: {},
})
const preferenceInfo = reactive({
  visible: false,
})
const formRefs = ref([])
const showSelectOrder = ref(false)
const defaultSelect = ref([])
const detailDialog = ref(false)
const detailId = ref('')
const showDetails = ref(false)
const licenseId = ref('')
const licencesSystemConfig = ref({})
const tableKey = ref(
  'purchApplicationDetailModify-com.slip.spd.entity.vo.purch.PurchApplicationDetailVO'
)
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canAddProduct = computed(() => {
  return formInfo.data.deptId && props.isSpecialEdit !== 1
})
const canRemoveProduct = computed(() => {
  return tableInfo.selections.length && props.isSpecialEdit !== 1
})

watch(
  () => tableInfo.data,
  () => {
    tableInfo.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price == null ? 0 : row.price)
      )
    })
  },
  {
    deep: true,
  }
)

let obj = {
  qty: {
    label: '申购数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    type: 'slot',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchApplication:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchApplication:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('purchApplication:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  beforeExportQty: {
    label: '上月出库量',
    value: 'beforeExportQty',
    type: 'column',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()

onMounted(() => {
  getValueList()
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  })
})

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(true)
    }
  })
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function largeMax(row) {
  if (
    systemConfig.value.use_convert_count_restrict == 1 &&
    formInfo.data.useId &&
    (row.maxConvertCount || row.maxConvertCount === 0)
  ) {
    return parseInt((row.maxConvertCount || 0) / row.unitConvertCoefficient)
  } else {
    return 99999999
  }
}
function smallMax(row) {
  if (
    systemConfig.value.use_convert_count_restrict == 1 &&
    formInfo.data.useId &&
    (row.maxConvertCount || row.maxConvertCount === 0)
  ) {
    return parseInt((row.maxConvertCount || 0) % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function addProduct() {
  if (!formInfo.data.deptId) {
    proxy
      .$confirm('请选择部门', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        openDeptWindow()
      })
    return
  }
  const idNotIn = tableInfo.data.map(function (item) {
    return item.productId
  })
  productInfo.query.queryParams.deptId = formInfo.data.deptId
  productInfo.query.queryMap.id.value = idNotIn.toString()
  productInfo.query.queryParams.orderId = props.orderId
  productInfo.visible = true
}
//删除产品
function removeProduct() {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      tableInfo.selectionsCopy = proxy.$fn.deepClone(tableInfo.selections)
      tableInfo.data = tableInfo.data.filter(
        (row) => !tableInfo.selections.includes(row)
      )
    })
}
//选择模板
function selectTemplate() {
  if (!formInfo.data.deptId) {
    proxy
      .$confirm('请选择部门', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        openDeptWindow()
      })
    return
  }
  purchTemplateInfo.query.deptId = formInfo.data.deptId
  purchTemplateInfo.query.templateType = 1
  purchTemplateInfo.visible = true
}
function selectPurchTemplateCallback(data) {
  if (data) {
    let ids = data.map((row) => row.id)
    let purchTemplateIds = String(ids)
    const params = {
      purchTemplateIdIn: purchTemplateIds,
      purchOrderId: props.orderId,
    }
    let selections = tableInfo.selectionsCopy
    getPurchTemplateDetailAll(params).then((resp) => {
      if (resp && resp.success) {
        resp.data = resp.data.filter((item) => {
          return tableInfo.data.every((el) => el.productId !== item.productId)
        })
        if (
          systemConfig.value.use_convert_count_restrict == 1 &&
          formInfo.data.useId
        ) {
          resp.data.forEach((item) => {
            if (selections.length) {
              selections.forEach((row) => {
                if (row.productId === item.productId) {
                  item.maxConvertCount = row.maxConvertCount
                  if (item.calcQty === 0) {
                    item['largeUnitQty'] = parseInt(
                      (item.maxConvertCount || 0) / item.unitConvertCoefficient
                    )
                    item['smallUnitQty'] = parseInt(
                      (item.maxConvertCount || 0) % item.unitConvertCoefficient
                    )
                  }
                }
              })
            }
          })
        }
        tableInfo.data = resp.data.concat(tableInfo.data)
      }
    })
  }
}
//选择产品
function selectProduct(rows) {
  if (rows) {
    rows = generateProductKey(rows)
    let selections = tableInfo.selectionsCopy
    const data = rows.map(function (item) {
      return {
        ...item,
        qty: 0,
        price: item.price || 0,
      }
    })
    if (
      systemConfig.value.use_convert_count_restrict == 1 &&
      formInfo.data.useId
    ) {
      data.forEach((item) => {
        if (selections.length) {
          selections.forEach((row) => {
            if (row.productId === item.productId) {
              item.maxConvertCount = row.maxConvertCount
              if (item.calcQty === 0) {
                item['largeUnitQty'] = parseInt(
                  (item.maxConvertCount || 0) / item.unitConvertCoefficient
                )
                item['smallUnitQty'] = parseInt(
                  (item.maxConvertCount || 0) % item.unitConvertCoefficient
                )
              }
            }
          })
        }
      })
    }
    tableInfo.data = data.concat(tableInfo.data)
  }
}
function _selectDept(row) {
  if (row) {
    if (row.id !== formInfo.data.deptId) {
      formInfo.data['deptName'] = row.name
      formInfo.data['deptId'] = row.id

      defaultSelect.value = []
      selectDeptProduct(row.id).then((res) => {
        if (res && res.success) {
          if (res.data.ownAllProduct == 0) {
            //不允许使用所有产品
            let deptProductIds = res.data.deptProductIds
            if (deptProductIds && deptProductIds.length) {
              tableInfo.data = tableInfo.data.filter((item) =>
                deptProductIds.includes(item.productId)
              )
            } else {
              tableInfo.data = []
            }
          } else {
            if (!(tableInfo.data && tableInfo.data.length)) return
            // 再次请求purch/applications/selectProductWithStock 更新库存量
            const ids = tableInfo.data.map(function (item) {
              return item.productId
            })
            console.log(ids)
            const params = {
              deptId: formInfo.data.deptId,
              createTime: formInfo.data.createTime,
              productIds: ids,
            }

            getLastAndDeptStock(params).then((res) => {
              if (res.success && res?.data?.details.length) {
                let details = res.data.details
                tableInfo.data.map((item, index) => {
                  item.deptAvailableStockQty =
                    details[index].deptAvailableStockQty
                  item.lastMonthExportQty = details[index].lastMonthExportQty
                })
              }
            })
          }
        }
      })
    }
  } else {
    formInfo.data['deptName'] = ''
    formInfo.data['deptId'] = ''
    tableInfo.data = []
    defaultSelect.value = []
  }
}
function openDeptWindow() {
  deptInfo.visible = true
}
function saveAndSubmit() {
  save('', '', '', true)
}
function save(eventObj, isSubmit, ids = undefined, isSaveAndSubmit) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const details = tableInfo.data
      .filter((item) => item.calcQty > 0)
      .map((item) => {
        let smallUnitQty = parseFloat(item.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(
          item.unitConvertCoefficient || 1
        )
        let largeUnitQty = parseFloat(item.largeUnitQty || 0)

        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        item.qty = proxy.$fn.qtyFormatter(
          proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        )
        item.sumAmount = proxy.$fn.accMul(
          proxy.$fn.accAdd(
            proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
            largeUnitQty
          ),
          parseFloat(item.price)
        )
        return {
          ...item,
          calcQty: calcQty,
        }
      })

    if (details.length === 0) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }
    if (details.length < tableInfo.data.length) {
      proxy
        .$confirm(`存在数量为0的产品，是否继续保存`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(() => {
          checkSave(details, isSubmit, ids, isSaveAndSubmit)
        })
        .catch()
    } else {
      checkSave(details, isSubmit, ids, isSaveAndSubmit)
    }
  })
}
function checkSave(details, isSubmit, ids, isSaveAndSubmit) {
  const data = formInfo.data
  data.isSpecialEdit = props.isSpecialEdit
  data.mergeDetails = proxy.$fn.filterBlacklist(details)
  applicationsValidatePlanRemind(data).then((res) => {
    if (res && res.success) {
      const api = data.id
        ? updatePurchApplication
        : isSaveAndSubmit === true
        ? createPurchApplicationAndSave
        : createPurchApplication
      api(data).then((resp) => {
        if (resp && resp.success) {
          if (isSubmit) {
            submitPurchApplication(ids).then((resp) => {
              if (resp.success) {
                tableInfo.refresh = Math.random()
                showDialog.value = false
                emit('returnModify', false)
              }
            })
          } else {
            showDialog.value = false
            emit('returnModify', false)
          }
        }
      })
    }
  })
}
//提交申购单
function submit(eventObj) {
  const ids = []
  ids.push(props.orderId)
  save(eventObj, true, ids)
}
//获取申购单明细
function getList() {
  purchApplicationDetailCustomizeListAll(filterInfo.query).then((resp) => {
    if (resp && resp.success) {
      if (props.isCopy) {
        resp.data.forEach((val) => {
          val.id = null
          val.orderId = null
          val.price = val.defaultSupplierPrice
          val.prePurchQty = null
          val.prePurchCalcQty = null
          val.actualPurchQty = null
          val.actualPurchCalcQty = null
        })
        tableInfo.data = resp.data
        formInfo.data.id = null
      } else {
        tableInfo.data = resp.data
      }
    }
  })
}
//获取申购单主表
function getMain(orderId) {
  getPurchApplication(orderId).then((resp) => {
    if (resp && resp.success) {
      if (props.isCopy) {
        formInfo.data.deptName = resp.data.deptName
        formInfo.data.deptId = resp.data.deptId
        formInfo.data.temporaryPurch = resp.data.temporaryPurch
        formInfo.data.temporaryPurchValue = resp.data.temporaryPurchValue
      } else {
        formInfo.data = resp.data
      }
      filterInfo.query.queryParams.deptId = formInfo.data.deptId
      getList()
    }
  })
}

function showLicenseDetail(id) {
  licenseId.value = id
  showDetails.value = true
}
function showDetail(row) {
  detailId.value = row.productId
  detailDialog.value = true
}
function getValueList() {
  getCoreSystemConfigGetConfigValue({
    systemConfigCode: 'license_nearly_effective',
  }).then((resp) => {
    if (resp && resp.success) {
      licencesSystemConfig.value = resp.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiffLicen(row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (Number(licencesSystemConfig.value) >= dataDiff) {
      return 'nearly-row'
    }
  }
  return ''
}
function tableCellClassName({ column, row }) {
  if (row.calcQty === 0 && column.property === 'qty') {
    return 'cell-color'
  }
  return ''
}
function getCustomize(update = undefined) {
  let param = {
    tableKey: tableKey.value,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      filterInfo.query.customizeUserVO = data
      filterInfo.query.queryMap.orderId.value = props.orderId
      if (update) {
        /*  let arr = []
        for (let key in data.detail) {
          arr.push(data.detail[key])
        }
        let sortArr = []
        arr.forEach((item) => {
          if (item.sortControllerType === 1) {
            sortArr.push({
              prop: item.fieldName,
              order: 'ascending',
            })
          } else if (item.sortControllerType === 2) {
            sortArr.push({
              prop: item.fieldName,
              order: 'descending',
            })
          }
        })
        if (sortArr.length) {
          proxy.$refs.table.$refs.table.sort(sortArr[0].prop, sortArr[0].order)
          console.log(tableInfo)
        } */
        return
      }
      if (props.orderId) {
        getMain(props.orderId)
      }
    }
  })
}
function generateProductKey(products) {
  return products.map((item) => {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate
    item._id = key
    return item
  })
}
</script>

<style scoped lang="scss">
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table .nearly-row) {
  background: #fceacb;
}
:deep(.el-table .expire-row) {
  background: #f5e4e4;
}
:deep(.el-table .cell-color) {
  background: #f4aed9bd;
}
// :deep(.el-table__body tr.hover-row > td) {
//   background-color: transparent !important;
// }
</style>
